<template>
  <div class="browse card">
    <h3 class="title">个微浏览视频号</h3>
    <el-form :model="addForm" :rules="addRules" ref="addFormRef">
      <p class="step-name">第一步：设置时间</p>
      <div class="step">
        <el-row :gutter="10">
          <el-col :span="7">
            <div class="time-range">
              <el-form-item prop="time">
                <el-time-picker
                  v-model="addForm.time"
                  @change="changeTime"
                  is-range
                  range-separator="-"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                />
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="4" v-if="aroundTime">
            <el-form-item prop="space" label="间隔时间">
              <el-input-number v-model="addForm.space" placeholder="间隔时间" :max="aroundTime" :min="0"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>

        <p class="step-name">第二步：设置点赞收藏频率</p>
        <div class="step">
          <el-row :gutter="10">
            <el-col :span="4">
              <el-switch v-model="addForm.collectAndLikeFlag" active-text="点赞收藏" inactive-text="不点赞收藏"></el-switch>
            </el-col>
            <el-col :span="3">
              <el-form-item prop="">
                <el-input v-model="addForm.likeProb" type="number"><template #append>%</template></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="2">点赞</el-col>
            <el-col :span="3">
              <el-form-item prop="">
                <el-input v-model="addForm.collectProb" type="number"><template #append>%</template></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="2">收藏</el-col>
          </el-row>
        </div>

        <p class="step-name">第三步：选择执行账号</p>
        <div class="step">
          <div class="checkbox">
            <el-form-item prop="accountList">
              <el-checkbox-group v-model="addForm.accountList">
                <el-checkbox
                  :class="item.accountType === '企微' ? 'green-text' : ''"
                  :label="item.accountName"
                  :value="item.accountId"
                  v-for="item of accountData.slice(0, 5)"
                  :key="item.accountId"
                />
              </el-checkbox-group>
            </el-form-item>
          </div>
          <div v-if="accountData.length > 5" class="more-btn">
            ......
            <el-button @click="toMore">选择更多</el-button>
          </div>
          <div v-if="addForm.accountList.length" class="account-info">
            已选择 <span>{{ addForm.accountList.length }}</span> 个账号
          </div>

          <div class="btns">
            <el-button type="success" :icon="Reading" @click="startBrowse">开始浏览</el-button>
            <el-button type="danger" :icon="Close" @click="stopBrowse">停止浏览</el-button>
          </div>
        </div>
      </div>
    </el-form>

    <div class="state-message" v-for="(item, index) of stateMessage" :key="index">
      {{ item[0] }}
    </div>
    <div class="state-message" v-for="(item, index) of stateLookMessage" :key="index">
      {{ item[0] }}
    </div>
  </div>
</template>

<script setup lang="ts">
import { Close, Reading } from "@element-plus/icons-vue";
import { ref } from "vue";
import { AccountList } from "@/api/interface";
import {
  getAccountListApi,
  lookTaskStateApi,
  startVideoTaskApi,
  stopVideoTaskApi,
  videoTaskStateApi
} from "@/api/modules/business";
import { useRouter } from "vue-router";
import { useUserStore } from "@/stores/modules/user";
import dayjs from "dayjs";
import { ElMessage, ElMessageBox } from "element-plus";

const router = useRouter();
const userStore = useUserStore();
const initForm = () => {
  return {
    time: [],
    space: 0,
    startTime: "",
    endTime: "",
    collectAndLikeFlag: false,
    collectProb: 0,
    likeProb: 0,
    accountList: []
  };
};
const addForm = ref(initForm());
const addFormRef = ref<any>(null);
const addRules = {
  time: { required: true, message: "请选择时间", trigger: "blur" },
  accountList: { required: true, message: "请选择账号", trigger: "blur" }
};
const accountData = ref<AccountList[]>([]);
const aroundTime = ref(0);
const stateMessage = ref<string[][]>([]);
const stateLookMessage = ref<string[][]>([]);

function changeTime(val: Date[] | null) {
  aroundTime.value = 0;
  addForm.value.space = 0;
  if (val) {
    const time = new Date(val[1]).getTime() - new Date(val[0]).getTime();
    aroundTime.value = time / 1000;
    addForm.value.startTime = dayjs(val[0]).format("HH:mm:ss");
    addForm.value.endTime = dayjs(val[1]).format("HH:mm:ss");
  } else {
    addForm.value.startTime = "";
    addForm.value.endTime = "";
  }
}

function startBrowse() {
  addFormRef.value.validate((valid: boolean) => {
    if (valid) {
      ElMessageBox.confirm("确认开始浏览？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(async () => {
        const data = await startVideoTaskApi(addForm.value);
        console.log("data", data);
        if (!data.result) return ElMessage.error(data.message);
        ElMessage.success(data.message || "操作成功");
        addForm.value = initForm();
        getState().then();
        getLookState().then();
      });
    }
  });
}

function stopBrowse() {
  ElMessageBox.confirm("确认停止浏览？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "error"
  }).then(async () => {
    const data = await stopVideoTaskApi();
    if (!data.result) return ElMessage.error(data.message);
    ElMessage.success(data.message || "操作成功");
    getState().then();
    getLookState().then();
  });
}

function toMore() {
  userStore.setTaskInfo(addForm.value);
  router.push({ name: "selectAccount", query: { type: "browseChannels" } });
}

async function getAccountData() {
  const data = await getAccountListApi({
    page: 1,
    size: 6,
    with_messages: true,
    type_list: "全部",
    group_list: "全部",
    state_list: "全部"
  });
  accountData.value = data.data || [];
}

async function getState() {
  const data = await videoTaskStateApi();
  if (data.result) stateMessage.value = data.messageList || [];
}

async function getLookState() {
  const data = await lookTaskStateApi();
  if (data.result) stateLookMessage.value = data.messageList || [];
}

getState();
getLookState();
getAccountData();

defineOptions({ name: "BrowseChannels" });
</script>

<style scoped lang="scss">
@import "./index";
</style>
